<template>
  <div class="employee_management_container">
    <div class="sidebar">
      <div class="btn_group">
        <HPlainButton v-show="notAllow == false" v-permission="'organ_edit'" @click="editOrganize"
          >部门编辑</HPlainButton
        >
        <HPlainButton v-permission="'organ_add'" @click="addOrganize">新增部门</HPlainButton>
      </div>
      <div class="line"></div>
      <el-tree
        class="tree"
        :data="trees"
        :props="defaultProps"
        :highlight-current="true"
        :accordion="true"
        default-expand-all
        node-key="id"
        :indent="14"
        :current-node-key="defaultKey"
        @node-click="handleNodeClick"
      />
    </div>
    <div class="line"></div>
    <div class="body">
      <div class="header">
        <HPlainButton v-permission="'organ_addEmp'" @click="addEmp">新增职员</HPlainButton>
        <div class="search">
          <el-input
            v-model.trim="name"
            placeholder="请输入姓名"
            class="input-name"
            clearable
            @keyup.enter="getAllEmp"
            @clear="getAllEmp"
          />
          <el-input
            v-model.trim="telephone"
            placeholder="请输入手机号"
            maxlength="11"
            class="input-name"
            clearable
            @keyup.enter="getAllEmp"
            @clear="getAllEmp"
          />
          <HButton type="primary" @click="getAllEmp">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
        </div>
      </div>
      <div class="table">
        <el-table
          ref="tableList"
          border
          stripe
          resizable
          :data="tableData"
          height="100%"
          @selection-change="handleChange"
        >
          <template #empty>
            <el-empty description="查无数据" />
          </template>
          <!--多选-->
          <el-table-column
            type="selection"
            width="40"
            :selectable="checkDisable"
            fixed="left"
            :align="'center'"
          />

          <!--序号-->
          <el-table-column
            show-overflow-tooltip
            type="index"
            label="序号"
            width="50"
            fixed="left"
            :align="'center'"
          />

          <!--职员姓名-->
          <el-table-column show-overflow-tooltip prop="name" label="职员姓名" min-width="120" />

          <!--职员手机-->
          <el-table-column show-overflow-tooltip prop="phone" label="职员手机" width="120" />

          <!--职员角色-->
          <el-table-column show-overflow-tooltip prop="role" label="职员角色" width="120" />
          <!-- 职职员号 -->
          <el-table-column show-overflow-tooltip prop="jobNumber" label="职员工号" width="90" />
          <!--是否职员主管-->
          <!-- <el-table-column
                show-overflow-tooltip
                prop="manager"
                label="是否职员主管"
                width="100"
              >
                <template #default="scope">
                  <span>
                    {{
                      scope.row.manager == null ? '系统超管' : scope.row.manager ? '是' : '否'
                    }}</span
                  >
                </template>
              </el-table-column> -->

          <!--创建时间-->
          <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />

          <!--更新时间-->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />

          <!--最后登录-->
          <el-table-column show-overflow-tooltip prop="loginTime" label="最后登录" width="170" />

          <!--状态-->
          <el-table-column prop="name" label="职员状态" width="80" fixed="right" :align="'center'">
            <template #default="scope">
              <div class="flex_justify_center">
                <HStatus v-if="!scope.row.depart">在职</HStatus>
                <HStatus v-if="scope.row.depart" type="info">离职</HStatus>
              </div>
            </template>
          </el-table-column>

          <!--操作-->
          <el-table-column show-overflow-tooltip fixed="right" label="操作" width="140">
            <template #default="scope">
              <el-space :size="0" :spacer="spacer">
                <HLink v-permission="'organ_viewEmp'" @click="viewEmpDetail(scope.row)">详细</HLink>
                <HLink
                  v-if="scope.row.superAccount == false"
                  v-permission="'organ_updateEmp'"
                  @click="changeEmp(scope.row)"
                  >修改</HLink
                >
                <h-link
                  v-if="scope.row.superAccount == false"
                  v-permission="'organ_deleteEmp'"
                  type="error"
                  @click="handleDelRole(scope.row)"
                  >删除</h-link
                >
              </el-space>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <div class="pagination">
        <Pagination
          ref="pagination"
          :list_total="total"
          @size-change="getAllEmp"
          @current-change="getAllEmp(false)"
        />
      </div>
    </div>

    <!-- 新增/编辑部门弹窗 -->
    <h-dialog v-model="addDialog" :title="organizeDialogTitle" :loading="saveOrganizeLoading">
      <el-form
        ref="ruleFormRef"
        label-position="top"
        inline-message
        class="modal_form_content"
        :rules="rules"
        :model="ruleForm"
      >
        <!--部门名称-->
        <el-form-item label="部门名称" prop="name">
          <el-input v-model.trim="ruleForm.name" clearable placeholder="请输入名称" />
        </el-form-item>

        <!--上级部门-->
        <el-form-item label="上级部门" prop="level">
          <el-select
            v-model="ruleForm.level"
            placeholder="请选择"
            filterable
            clearable
            remote
            reserve-keyword
            remote-show-suffix
            :loading="organizeLoading"
            :remote-method="searchOrganizeSelect"
          >
            <el-option label="独立组织" value="0" />
            <el-option
              v-for="item in organizeSelect"
              :key="item.id"
              :label="item.name"
              :disabled="item.id == ruleForm.id"
              :value="item.id"
            >
              <span>{{ item.name }}</span>
              <span v-show="item.system" class="organize-tip">
                {{ item.system == true ? '系统组织' : '' }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <!--部门主管-->
        <el-form-item label="部门主管" prop="manegerEmpId">
          <el-select
            v-model="ruleForm.manegerEmpId"
            placeholder="请选择"
            filterable
            clearable
            remote
            reserve-keyword
            remote-show-suffix
            :loading="empLoading"
            :remote-method="searchEmpSelect"
          >
            <el-option
              v-for="item in empSelect"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="部门状态" class="form-item">
              <el-radio-group v-model="status" class="el-group">
                <el-radio :value="false">
                  <span class="bg_text">启用</span>
                </el-radio>
                <el-radio :value="true">
                  <span class="bg_text">禁用</span>
                </el-radio>
              </el-radio-group>
            </el-form-item> -->
      </el-form>

      <template #footer>
        <HPlainBgButton
          v-show="organizeDialogTitle === '编辑部门'"
          is-modal
          type="error"
          @click="deleOrganize"
          >删除
        </HPlainBgButton>
        <HButton
          is-modal
          type="primary"
          :loading="searchBtnLoading == true"
          @click="saveAddOrganize(ruleFormRef)"
          >保存
        </HButton>
        <HButton is-modal @click="addDialog = false"> 取消 </HButton>
      </template>
    </h-dialog>

    <!-- 新增/修改职员弹窗 -->
    <h-dialog
      v-model="addDialog2"
      :title="empDialogTitle"
      :loading="saveEmpLoading || getEmpInfoLoading"
      @close="onHideStaffDialog"
    >
      <el-form
        ref="empFormRef2"
        label-position="top"
        class="modal_form_content"
        inline-message
        :model="empForm"
        :rules="empRules"
        @submit.prevent="() => {}"
      >
        <el-form-item
          label="手机号"
          prop="phone"
          :rules="[
            { required: true, message: '请输入正确的手机号', trigger: 'blur' },
            { validator: phone(empForm.phone), trigger: 'blur' },
          ]"
        >
          <div style="display: flex; gap: 5px; width: 100%">
            <el-input
              v-model.trim="empForm.phone"
              class="item-input"
              maxlength="11"
              clearable
              placeholder="请输入手机号"
              @keyup.enter="getStaffInfoByPhone"
            />
            <HPlainButton :loading="searchBtnLoading" @click="getStaffInfoByPhone"
              >查询</HPlainButton
            >
          </div>
        </el-form-item>
        <template v-if="showInfo == true">
          <el-form-item v-if="empForm.accountId == ''" label="密码" prop="password">
            <el-input
              v-model.trim="empForm.password"
              placeholder="请输入密码"
              clearable
              :type="passwordType"
            >
              <template #suffix>
                <div class="show-pwd" @click="showPwd">
                  <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model.trim="empForm.name" clearable placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="工号" prop="jobNumber">
            <el-input
              v-model.trim="empForm.jobNumber"
              maxlength="20"
              clearable
              placeholder="请输入工号"
            />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model.trim="empForm.nickname" clearable placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="所属部门" prop="level">
            <el-select
              v-model="empForm.level"
              placeholder="请选择"
              filterable
              clearable
              remote
              reserve-keyword
              remote-show-suffix
              :loading="organizeLoading"
              :remote-method="searchOrganizeSelect"
            >
              <el-option
                v-for="item in organizeSelect"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <span>{{ item.name }}</span>
                <span v-show="item.system" class="organize-tip">
                  {{ item.system == true ? '系统组织' : '' }}
                </span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="职员角色" prop="author">
            <el-select
              v-model="empForm.author"
              placeholder="请选择"
              filterable
              clearable
              remote
              reserve-keyword
              remote-show-suffix
              :loading="roleLoading"
              :remote-method="searchRoleSelect"
            >
              <el-option
                v-for="item in roleSelect"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="角色状态" class="same_line">
            <el-radio-group v-model="empForm.depart">
              <el-radio :value="false" size="small">在职</el-radio>
              <el-radio :value="true" size="small">离职</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <template v-if="showInfo == true">
          <h-button is-modal type="primary" @click="saveAddEmp(empFormRef2)">保存</h-button>
          <h-button is-modal @click="onHideStaffDialog">取消</h-button>
        </template>
      </template>
    </h-dialog>

    <!--职员信息弹窗-->
    <template v-if="currentVisibleEmp">
      <EmpDetailModal v-model="empDetailModalVisible" :info="(currentVisibleEmp as EmpDetail)" />
    </template>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, reactive, watch, h, nextTick } from 'vue'
  import { ElDivider, FormInstance, TableInstance } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getOrganizeList,
    saveOrganize,
    getEmpList,
    saveEmp,
    getInfoAccount,
    rolePageSelecct,
    empPageSelecct,
    organizePageSelecct,
    getInfoOrganize,
    deleteOrganize,
    deleteEmp,
    getInfoEmp,
  } from '@/api/organize'
  import { phone, passwordLength, EnglishName } from '@/utils/validate'
  import EmpDetailModal from './components/EmpDetail.vue'
  import { EmpDetail } from './types'
  import { useEmpDetail } from './services'
  import routeComponentName from '@/config/route-component-name'

  defineOptions({
    name: routeComponentName.accountPermission.staffManger,
  })

  const { empInfo, getEmpInfoLoading, getEmpInfoFn } = useEmpDetail()

  const handleDelRole = (employee: EmpDetail) => {
    if (tableList.value) {
      tableList.value.toggleRowSelection(employee, true)
      empForm.empId = employee.empId
      deleEmp()
    }
  }

  const onHideStaffDialog = () => {
    addDialog2.value = false
    resetStaffForm()
  }

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 职员详情弹窗状态
  const empDetailModalVisible = ref(false)

  const loading = ref(false) // 页面加载loading
  const defaultKey = ref('')

  const trees = ref([]) // 组织列表
  const organizeId = ref() // 组织ID
  const organizeIds = ref([]) // 组织ID集合

  // 部门表单数据
  const ruleForm = reactive({
    name: '', // 部门名称
    level: '', // 部门层级
    manegerEmpId: '', // 部门主管
    id: '',
  })

  // 表单元素
  const ruleFormRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
    level: [{ required: true, message: '请选择部门层级', trigger: 'blur' }],
    manegerEmpId: [{ required: true, message: '请选择部门主管', trigger: 'blur' }],
  })

  const pagination = ref() // 分页dom
  const limit = ref() // 每页显示数量
  const page = ref() // 当面页码
  const total = ref() // 总数目

  // 搜索框
  const name = ref('') // 姓名
  const telephone = ref('') // 手机号

  const tableList = ref<TableInstance | null>(null) // 列表dom
  const tableData = ref([]) // 组织职员列表
  const showInfo = ref(false)
  const searchBtnLoading = ref(false)
  const empFormRef = ref<FormInstance>()
  const empFormRef2 = ref<FormInstance | null>(null)

  // 职员表单数据
  const empForm = reactive({
    accountId: '', // 人员账号ID
    id: '', // 人员ID
    password: '', // 密码
    empId: '', // 职员ID
    name: '', // 姓名
    jobNumber: '', //职员工号
    nickname: '', // 昵称
    phone: '', // 手机号
    level: '', // 部门层级
    author: '', // 角色
    loginTime: '',
    depart: false,
  })

  // 验证规则
  const empRules = reactive({
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      // { validator: password(empForm.password), trigger: 'blur' },//saas
      { validator: passwordLength(empForm.password), trigger: 'blur' }, //saas
    ],
    jobNumber: [
      { required: false, trigger: 'blur' },
      { min: 0, max: 16, message: '最大长度16个字符', trigger: 'blur' },
      { validator: EnglishName(empForm.jobNumber), trigger: 'blur' },
    ],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    level: [{ required: true, message: '请选择所属部门', trigger: 'blur' }],
    author: [{ required: true, message: '请选择职员角色', trigger: 'blur' }],
  })

  const passwordType = ref('password')
  const showPwd = () => {
    if (passwordType.value === 'password') {
      passwordType.value = ''
    } else {
      passwordType.value = 'password'
    }
  }

  // 弹窗显示
  const addDialog = ref(false) // 添加组织
  const addDialog2 = ref(false) // 添加职员

  // 标题
  const organizeDialogTitle = ref('')
  const empDialogTitle = ref('')

  // 弹窗loading
  const editLoading = ref(false)

  const notAllow = ref(true) // 是否允许修改组织
  const parentId = ref() // 父级组织ID

  // 下拉数据
  const organizeSelect = ref() // 企业组织
  const empSelect = ref() // 企业职员
  const roleSelect = ref() // 企业角色

  // 搜索loading
  const organizeLoading = ref(false)
  const empLoading = ref(false)
  const roleLoading = ref(false)

  // 搜索值
  const empVal = ref('') // 组织
  const organizeVal = ref('') // 职员
  const roleVal = ref('') // 角色

  // 树型列表配置选项
  const defaultProps = {
    children: 'organizesVos',
    label: 'name',
  }

  // 判断是否可选
  const checkDisable = (row) => {
    if (row.superAccount == true) {
      return false // 不可选
    } else {
      return true // 可选
    }
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.empId) == -1) {
          selecttion.value.push(item.empId)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.empId)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取组织列表
  const getAllOrganize = async () => {
    loading.value = true
    await getOrganizeList().then((res) => {
      trees.value = res.data.data.rows
      nextTick(() => {
        defaultKey.value = trees.value[0].id
        loading.value = false
      })
    })
  }

  // 获取职员列表
  const getAllEmp = async (val = true) => {
    loading.value = true
    if (val) pagination.value.setPage()
    limit.value = pagination.value.size
    page.value = pagination.value.current
    const data = {
      limit: limit.value,
      name: name.value,
      organizeId: organizeId.value == undefined ? '' : organizeId.value,
      page: page.value,
      phone: telephone.value,
    }
    await getEmpList(data).then((res) => {
      total.value = parseInt(res.data.data.total)
      tableData.value = res.data.data.rows
      loading.value = false
    })
  }

  onMounted(async () => {
    loading.value = true
    await getAllOrganize()
    await getAllEmp()
    loading.value = false
  })

  // 点击部门查找职员
  const handleNodeClick = (data) => {
    parentId.value = data.parentId
    defaultKey.value = data.id
    if (data.system == false) {
      organizeId.value = data.id
      notAllow.value = false
    } else {
      organizeId.value = ''
      notAllow.value = true
    }
    getAllEmp()
  }

  // 获取组织下拉数据
  const getOrganizeSelecct = async (n) => {
    const params = {
      name: n,
      limit: limit.value,
      page: page.value,
    }
    await organizePageSelecct(params).then((res) => {
      organizeSelect.value = res.data.data.rows
    })
  }

  // 搜索组织下拉数据
  const searchOrganizeSelect = (query: string) => {
    organizeVal.value = query
    if (query) {
      organizeLoading.value = true
      setTimeout(async () => {
        organizeLoading.value = false
      }, 1000)
    }
  }

  // 获取职员下拉数据
  const getEmpSelecct = async (n) => {
    const params = {
      name: n,
      limit: limit.value,
      page: page.value,
    }
    await empPageSelecct(params).then((res) => {
      empSelect.value = res.data.data.rows
    })
  }

  // 搜索职员下拉数据
  const searchEmpSelect = (query: string) => {
    empVal.value = query
    if (query) {
      empLoading.value = true
      setTimeout(async () => {
        empLoading.value = false
      }, 1000)
    }
  }

  // 获取角色下拉数据
  const getRoleSelecct = async (n) => {
    const params = {
      name: n,
      limit: limit.value,
      page: page.value,
    }
    await rolePageSelecct(params).then((res) => {
      roleSelect.value = res.data.data.rows
    })
  }

  // 搜索角色下拉数据
  const searchRoleSelect = (query: string) => {
    roleVal.value = query
    if (query) {
      roleLoading.value = true
      setTimeout(async () => {
        roleLoading.value = false
      }, 1000)
    }
  }

  // 监听下拉数据变化时是否进行搜索
  watch(
    // 组织
    () => organizeVal.value,
    (newVal, oldVal) => {
      if (oldVal != undefined) {
        getOrganizeSelecct(newVal)
      }
    },
  )
  watch(
    // 职员
    () => empVal.value,
    (newVal, oldVal) => {
      if (oldVal != undefined) {
        getEmpSelecct(newVal)
      }
    },
  )
  watch(
    // 角色
    () => roleVal.value,
    (newVal, oldVal) => {
      if (oldVal != undefined) {
        getRoleSelecct(newVal)
      }
    },
  )

  // 新增部门
  const addOrganize = () => {
    organizeDialogTitle.value = '新增部门'
    getOrganizeSelecct('')
    getEmpSelecct('')
    ruleForm.name = ''
    ruleForm.manegerEmpId = ''
    ruleForm.id = ''
    ruleForm.level = defaultKey.value
    addDialog.value = true
  }

  // 编辑部门
  const editOrganize = () => {
    organizeDialogTitle.value = '编辑部门'
    editLoading.value = true
    getOrganizeSelecct('')
    getEmpSelecct('')
    getInfoOrganize(defaultKey.value).then((res) => {
      ruleForm.name = res.data.data.row.name
      ruleForm.level = res.data.data.row.parentId
      ruleForm.manegerEmpId = res.data.data.row.manegerEmpId
      ruleForm.id = res.data.data.row.id
      editLoading.value = false
    })
    addDialog.value = true
  }

  // 保存部门
  const saveOrganizeLoading = ref(false)
  const saveAddOrganize = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      manegerEmpId: ruleForm.manegerEmpId,
      name: ruleForm.name,
      parentId: ruleForm.level,
    }
    const data2 = {
      id: organizeId.value,
      manegerEmpId: ruleForm.manegerEmpId,
      name: ruleForm.name,
      parentId: ruleForm.level,
    }
    formEl.validate(async (valid) => {
      if (valid) {
        saveOrganizeLoading.value = true
        if (organizeDialogTitle.value == '编辑部门') {
          // 编辑
          saveOrganize(data2).then((res) => {
            saveOrganizeLoading.value = false
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              addDialog.value = false
              getAllOrganize()
              loading.value = false
            } else {
              ElMessage({
                message: res.data.message,
                type: 'warning',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              return
            }
          })
        } else {
          // 新增
          saveOrganize(data).then((res) => {
            saveOrganizeLoading.value = false
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              addDialog.value = false
              getAllOrganize()
              loading.value = false
            } else {
              ElMessage({
                message: res.data.message,
                type: 'warning',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              return
            }
          })
        }
      } else {
        return
      }
    })
  }

  // 删除部门
  const deleOrganize = () => {
    if (organizeIds.value.indexOf(organizeId.value) == -1) {
      organizeIds.value.push(organizeId.value)
    }
    ElMessageBox({
      type: 'error',
      title: '提示',
      message: '确认删除该部门?',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      await deleteOrganize(organizeIds.value).then((res) => {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      })
      addDialog.value = false
      getAllOrganize()
    })
  }

  // 添加职员
  const addEmp = () => {
    empDialogTitle.value = '新增职员'
    resetStaffForm()
    showInfo.value = false
    getOrganizeSelecct('')
    getRoleSelecct('')
    empForm.level = defaultKey.value
    addDialog2.value = true
  }

  // 修改职员
  const changeEmp = (obj) => {
    getOrganizeSelecct('')
    getRoleSelecct('')
    empDialogTitle.value = '修改职员'
    showInfo.value = true
    empForm.id = obj.id
    empForm.phone = obj.phone
    empForm.name = obj.name
    empForm.nickname = obj.nickname
    empForm.empId = obj.empId
    empForm.level = defaultKey.value
    empForm.depart = obj.depart
    empForm.jobNumber = obj.jobNumber
    getInfoEmp(obj.empId).then((res) => {
      empForm.accountId = res.data.data.row.accountId
      empForm.author = res.data.data.row.roleId
    })
    addDialog2.value = true
  }

  // 保存职员
  const saveEmpLoading = ref(false)
  const saveAddEmp = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      accountId: empForm.accountId,
      depart: empForm.depart,
      name: empForm.name,
      nickname: empForm.nickname,
      organizeId: empForm.level,
      password: empForm.password,
      phone: empForm.phone,
      roleId: empForm.author,
      jobNumber: empForm.jobNumber,
    }
    const data2 = {
      id: empForm.empId,
      accountId: empForm.accountId,
      depart: empForm.depart,
      name: empForm.name,
      nickname: empForm.nickname,
      organizeId: empForm.level,
      password: empForm.password,
      phone: empForm.phone,
      roleId: empForm.author,
      jobNumber: empForm.jobNumber,
    }
    formEl.validate(async (valid) => {
      if (valid) {
        saveEmpLoading.value = true
        if (empDialogTitle.value == '修改职员') {
          // 修改
          saveEmp(data2).then((res) => {
            saveEmpLoading.value = false
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              addDialog2.value = false
              getAllEmp()
              loading.value = false
            } else {
              ElMessage({
                message: res.data.message,
                type: 'warning',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              return
            }
          })
        } else {
          // 新增
          saveEmp(data).then((res) => {
            saveEmpLoading.value = false
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              formEl.resetFields()
              empFormRef.value?.resetFields()
              addDialog2.value = false
              getAllEmp()
              loading.value = false
            } else {
              ElMessage({
                message: res.data.message,
                type: 'warning',
                duration: 5000,
                plain: true,
                showClose: true,
              })
              return
            }
          })
        }
      } else {
        return
      }
    })
  }

  // 当前查看的职员信息
  const currentVisibleEmp = ref<null | EmpDetail>(null)

  // 查看职员详细
  const viewEmpDetail = (obj: EmpDetail) => {
    currentVisibleEmp.value = { ...obj }
    empDetailModalVisible.value = true
  }

  // 删除职员
  const deleEmp = () => {
    let tmp = []
    tmp.push(empForm.empId)
    ElMessageBox({
      type: 'error',
      title: '提示',
      message: '确认删除该职员?',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      await deleteEmp(tmp, defaultKey.value).then((res) => {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 5000,
          plain: true,
          showClose: true,
        })
      })
      addDialog2.value = false
      getAllEmp()
    })
  }

  const resetStaffForm = () => {
    Object.assign(empForm, {
      accountId: '',
      id: '',
      password: '',
      empId: '',
      name: '',
      jobNumber: '',
      nickname: '',
      phone: '',
      level: '',
      author: '',
      loginTime: '',
      depart: false,
    })
  }

  const getStaffInfoByPhone = async () => {
    if (!empFormRef2.value) {
      return
    }
    try {
      await empFormRef2.value.validateField('phone')
      const res = await getInfoAccount(empForm.phone)
      showInfo.value = true
      const tempPhone = empForm.phone
      resetStaffForm()
      empForm.phone = tempPhone
      empForm.name = res.data.data.row.name
      empForm.nickname = res.data.data.row.nickname
      empForm.accountId = res.data.data.row.id
      if (res.data.data.row.id && res.data.data.row.empId) {
        await getEmpInfoFn(res.data.data.row.id, res.data.data.row.empId)
        if (empInfo.value) {
          empForm.level = empInfo.value.organizeId
          empForm.author = empInfo.value.roleId
          empForm.id = res.data.data.row.empId
          empForm.name = res.data.data.row.name
          empForm.nickname = res.data.data.row.nickname
          empForm.accountId = res.data.data.row.id
          empForm.jobNumber = empInfo.value.jobNumber
          searchBtnLoading.value = false
          empFormRef2.value.clearValidate()
        }
      }
    } catch (error) {
      // error
    }
  }
</script>

<style scoped lang="scss">
  .employee_management_container {
    height: calc(100vh - 92px - 24px);
    box-sizing: border-box;
    padding: 12px;
    margin: 12px;
    background-color: #fff;
    display: flex;
    column-gap: 12px;

    .sidebar {
      width: 250px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;

      .btn_group {
        display: flex;
        column-gap: 5px;
        justify-content: flex-start;
      }

      .line {
        width: 100%;
        height: 1px;
        background-color: #ebeef5;
        margin: 13px 0;
      }

      :deep(.el-tree) {
        background-color: unset;
        .el-tree-node__content {
          font-size: 12px;
          padding: 3px;
        }
      }
    }

    .line {
      width: 1px;
      background-color: #ebeef5;
    }

    .body {
      width: calc(100% - 250px - 25px);
      display: flex;
      flex-direction: column;
      row-gap: 12px;
      height: 100%;
      box-sizing: border-box;

      .header {
        display: flex;
        justify-content: space-between;

        .search {
          display: flex;
          column-gap: 5px;

          :deep(.el-input) {
            width: 128px;
          }
        }
      }

      .table {
        max-height: calc(100% - 80px);

        :deep(.el-table__empty-block) {
          height: unset !important;
        }
      }

      .pagination {
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
